import { useRequest } from 'ahooks';
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { userLoginApi } from '../../../api'
import { saveUserData } from '../../../store/reducers/user'
import MD5 from 'md5'
import { useRef } from "react";
export function useLogin () {
    const dispatch  = useDispatch()
    const navigate = useNavigate()
    const captchaRef = useRef()

    const { loading, run, error } = useRequest(userLoginApi, {
        manual: true,
        onSuccess: res => {
            dispatch(saveUserData(res))
            navigate('/')
        },
        onError: error => {
            captchaRef.current && captchaRef.current.refreshCode()
        }
    })
    const handleLogin = loginData => {
        const copyData = JSON.parse(JSON.stringify(loginData))
        copyData.password = copyData.password.length === 32 ? copyData.password :  MD5(copyData.password)
        run(copyData)
    }
    return {
        loading,
        handleLogin,
        error,
        captchaRef
    }
}
